package com.sinszm.wx.pay;

import com.sinszm.common.exception.ApiException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Optional;

import static com.sinszm.wx.exception.WxApiError.WX_PAY_ERROR_003;
import static com.sinszm.wx.exception.WxApiError.WX_PAY_ERROR_004;

/**
 * 支付工厂
 *
 * @author chenjianbo
 */
@Component
public class PayFactory {

    @Autowired
    private ApplicationContext context;

    /**
     * 获得支付方式通道
     * @param platform
     */
    public PayApi factory(PayPlatform platform) {
        if (platform == null) {
            throw new ApiException(WX_PAY_ERROR_003);
        }
        Map<String, PayApi> map = context.getBeansOfType(PayApi.class);
        if (map.isEmpty()) {
            throw new ApiException(WX_PAY_ERROR_004);
        }
        Optional<Map.Entry<String, PayApi>> optional = map.entrySet()
                .stream()
                .filter(pre -> pre.getKey().equalsIgnoreCase(platform.name()))
                .findFirst();
        if (optional.isPresent()) {
            return context.getBean(optional.get().getValue().getClass());
        }
        throw new ApiException(WX_PAY_ERROR_004);
    }

}
